<template>
  <el-image
    :class="['image__preview-box', initShow ? 'init_show' : '']"
    :src="`${realSrc}`"
    :fit="fit"
    ref="imageRef"
    :preview-src-list="realSrcList"
    :initial-index="initialIndex"
    @close="handleClose"
    preview-teleported>
    <template #error>
      <div class="image-slot">
        <el-icon><picture-filled /></el-icon>
      </div>
    </template>
  </el-image>
</template>

<script setup name="ImagePreview">
  import { staticUrl } from '@/utils/frame'

  const props = defineProps({
    initShow: Boolean,
    src: {
      type: [String, Array],
      default: ''
    },
    fit: {
      type: String,
      default: 'cover'
    },
    list: {
      type: [String, Array],
      default: ""
    }
  })

  const realSrc = computed(() => {
    if (!props.src) return ''
    return staticUrl(props.src.split(',')[0])
  })

  const realSrcList = computed(() => {
    if (props.list) {
	  let list1 = Array.isArray(props.list) ? props.list : props.list.split(',')
	  if (list1.length) return list1.map(item => staticUrl(item))
    }
    if (!props.src) return []
    // 首先将值转为数组
    let real_src_list = Array.isArray(props.src) ? props.src : props.src.split(',')
    let srcList = []
    real_src_list.forEach(item => {
      srcList.push(staticUrl(item))
    })
    return srcList
  })
  
  
  const initialIndex = computed(() => {
    let index = 0
    if (!realSrcList.value.length){
      index = realSrcList.value.findIndex(item => item === realSrc.value)
    }
    return index > -1 ? index : 0
  })

  const imageRef = useTemplateRef('imageRef')
  onMounted(() => {
    if (props.initShow) {
      imageRef.value.showPreview()
    }
  })

  const emit = defineEmits(['close'])
  function handleClose() {
    emit('close')
  }
</script>

<style lang="scss" scoped>
  .init_show {
    width: 0 !important;
    height: 0 !important;
    display: block !important;
  }
  .el-image {
    border-radius: 5px;
    background-color: #ebeef5;
    box-shadow: 0 0 5px 1px #ccc;
    :deep(.el-image__inner) {
      transition: all 0.3s;
      cursor: pointer;
      &:hover {
        transform: scale(1.2);
      }
    }
    :deep(.image-slot) {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      color: #909399;
      font-size: 30px;
    }
  }
</style>
